package xcmg.device.service.purchase;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.basic.MaterialsPurchaseInfo;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.basic.MaterialsPurchaseInfoMapper;
import xcmg.device.infra.ErrorCode;
import yb.ecp.fast.infra.infra.log.LogHelper;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author wangyong
 */
@Service
public class MaterialsPurchaseInfoService {

    @Autowired
    private MaterialsPurchaseInfoMapper materialsPurchaseInfoMapper;

    @Autowired
    private CompanyInfoMapper companyInfoMapper;

//    @Transactional(rollbackFor = Exception.class)
//    public List<MaterialsPurchaseInfo> syncMaterialsPurchaseInfo(String orgId, String materialsNo) {
//        CompanyInfoDO companyInfoDO = companyInfoMapper.item(orgId);
//        if (null == companyInfoDO || null == companyInfoDO.getSapCode()) {
//            LogHelper.error("企业信息或者sap编码为空。orgId:" + orgId, ErrorCode.Failure.getCode());
//            return null;
//        }
//        materialsPurchaseInfoMapper.delete(orgId, materialsNo);
//        List<MaterialsPurchaseInfo> purchaseInfosSAP = getMaterialsPurchaseInfoFromSap(companyInfoDO.getSapCode(), materialsNo);
//        if (CollectionUtils.isEmpty(purchaseInfosSAP)) {
//            return null;
//        }
//        for (MaterialsPurchaseInfo info : purchaseInfosSAP) {
//            info.setOrgId(orgId);
//            materialsPurchaseInfoMapper.insert(info);
//        }
//        return purchaseInfosSAP;
//    }


//    /**
//     * 从sap获取零件供应商信息
//     *
//     * @param sapCode
//     * @param materialsNo
//     * @return
//     */
//    public List<MaterialsPurchaseInfo> getMaterialsPurchaseInfoFromSap(String sapCode, String materialsNo) {
//
//        ImportParam importParam = new ImportParam();
//        Map<String, String> map = new HashMap<>(16);
//        map.put("WERKS", sapCode);
//        importParam.setFunction("ZPMSBJ_GET_INFORMATION");
//        importParam.setCommonParamMap(map);
//
//        Map<String, List<Map<String, String>>> tableParamMap = new HashMap<>(16);
//        List<Map<String, String>> list = new ArrayList<>();
//
//        Map<String, String> mapd = new HashMap<>();
//        mapd.put("MATNR", materialsNo);
//        list.add(mapd);
//        tableParamMap.put("MATNR_IN", list);// 传入内表
//        importParam.setTableParamMap(tableParamMap);
//        importParam.setTable("PURINFOOUT");// 传出内表
//        importParam.setSapCode(sapCode);
//        OutputParam outputParam = SAPCommonUtil.getData(importParam);
//        if (null == outputParam || outputParam.getCode() != 0) {
//            LogHelper.error("sap返回值为null", ErrorCode.RequestIdError.getCode());
//            return null;
//        }
//
//        List<Map<String, String>> dataList = outputParam.getDataList();
//        if (CollectionUtils.isEmpty(dataList)) {
//            return null;
//        }
//        return assemblyPurchaseInfo(dataList);
//
//    }

    private List<MaterialsPurchaseInfo> assemblyPurchaseInfo(List<Map<String, String>> dataList) {
        List<MaterialsPurchaseInfo> purchaseInfoVOS = new ArrayList<>();
        Date now = new Date();
        for (Map<String, String> resultMap : dataList) {
            MaterialsPurchaseInfo purchaseInfo = new MaterialsPurchaseInfo();
            purchaseInfo.setMaterialsNo(resultMap.get("MATNR"));//零件号
            purchaseInfo.setMaterialsDes(resultMap.get("MAKTX"));//零件名称（短文本）
            purchaseInfo.setSupplierSapCode(resultMap.get("LIFNR"));//供应商或债权人的帐号
            purchaseInfo.setSupplierName(resultMap.get("NAME1"));//名称 1
            String price = resultMap.get("KBETR");//价格 (条件金额或百分数 )
            purchaseInfo.setPrice(StringUtils.isNotBlank(price) ? new BigDecimal(price) : BigDecimal.ZERO);
            purchaseInfo.setPriceUnit(resultMap.get("KPEIN"));//条件定价单位
            purchaseInfo.setBaseUnit(resultMap.get("MEINS"));//基本计量单位

            String startTimeStr = resultMap.get("DATAB");//条件记录有效起始日
            String endTimeStr = resultMap.get("DATBI");//条件记录有效截止日期
            purchaseInfo.setStartTime(parseGMTDate(startTimeStr));
            purchaseInfo.setEndTime(parseGMTDate(endTimeStr));
            purchaseInfo.setRecordingNo(resultMap.get("KNUMH"));//条件记录号
            purchaseInfo.setIdentification(resultMap.get("EVERS"));//暂估标识
            purchaseInfo.setPurchaseSapCode(resultMap.get("EKORG"));//采购方sapCode
            purchaseInfo.setFactorySapCode(resultMap.get("WERKS"));//主机厂sapCode
            purchaseInfo.setRecordingCategory(resultMap.get("ESOKZ"));//采购信息记录分类
            String deliverySpend = resultMap.get("APLFZ");//交货期（交货所需时间）
            if (StringUtils.isNotBlank(deliverySpend)) {
                purchaseInfo.setDeliverySpend(new BigDecimal(deliverySpend));
            }
            purchaseInfo.setUpdateTime(now);
            purchaseInfoVOS.add(purchaseInfo);
        }
        return purchaseInfoVOS;
    }


    private Date parseGMTDate(String dateGMT) {
        if (StringUtils.isBlank(dateGMT)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'GMT+08:00' yyyy", Locale.US);
        try {
            return sdf.parse(dateGMT);
        } catch (ParseException e) {
            return null;
        }
    }

    public List<MaterialsPurchaseInfo> selectByOrgIdAndMaterialNoAndSupplierCode(String materialsNo, String orgId, String supplierCode) {
        return materialsPurchaseInfoMapper.selectByOrgIdAndMaterialNoAndSupplierCode(materialsNo, orgId, supplierCode);
    }
}
